import cv2
import numpy as np
import json

# 读取TIFF文件
tiff_file = '/Users/daxiang/Downloads/haoping.tif'
png_file = '/Users/daxiang/Downloads/aa.png'
image = cv2.imread(png_file, cv2.IMREAD_GRAYSCALE)

# 阈值分割，将图像转换为二值图像
_, binary_image = cv2.threshold(image, 0, 255, cv2.THRESH_BINARY)

kernel = np.ones((11,11), np.uint8)
# 膨胀操作去除内部杂点噪音  eroded
for i in range(5):
    binary_image = cv2.dilate(binary_image , kernel, iterations=1)

cv2.imshow('Image', binary_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

# 检测轮廓
contours, _ = cv2.findContours(binary_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

print("------contours: " , contours)

# 轮廓近似
epsilon = 0.01 * cv2.arcLength(contours[0], True)
approx = cv2.approxPolyDP(contours[0], epsilon, True)

# 获取地理转换信息（根据您的TIFF文件的实际情况进行调整）
geotransform = (111.2279051057111, 0.000011751600569, 0, 32.85772767224697, 0, -0.000009912427693)

contour_image = np.zeros_like(binary_image)
cv2.drawContours(contour_image, contours, -1, 255, 1)

# 提取轮廓边界线上的所有点的坐标
points = np.argwhere(contour_image == 255)

# 转换为经纬度坐标
latitudes = geotransform[3] + points[:, 0] * geotransform[5]
longitudes = geotransform[0] + points[:, 1] * geotransform[1]

# 创建GeoJSON对象
geojson = {
    "type": "Feature",
    "geometry": {
        "type": "LineString",
        "coordinates": []
    }
}

# 添加经纬度坐标到GeoJSON对象
for latitude, longitude in zip(latitudes, longitudes):
    geojson["geometry"]["coordinates"].append([longitude, latitude])

# 将GeoJSON对象转换为字符串
geojson_str = json.dumps(geojson)

output_file = '/Users/daxiang/Downloads/haoping.json'
with open(output_file, 'w') as f:
    f.write(geojson_str)

